

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="caoyusang">
  <meta name="keywords" content="">
  <title>MyBatis基础知识 - caoyusang的科研日常</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>caoyusang</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/7.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-12-14 20:31" pubdate>
        2020年12月14日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      69
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">MyBatis基础知识</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 个月前
                
              </p>
            
            <div class="markdown-body" id="post-body">
              <h3 id="MyBatis框架使用"><a href="#MyBatis框架使用" class="headerlink" title="MyBatis框架使用"></a>MyBatis框架使用</h3><h2 id="1-导入mybatis的jar包"><a href="#1-导入mybatis的jar包" class="headerlink" title="1. 导入mybatis的jar包"></a>1. 导入mybatis的jar包</h2><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.5.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
<h2 id="2-根据数据表建立实体类"><a href="#2-根据数据表建立实体类" class="headerlink" title="2. 根据数据表建立实体类"></a>2. 根据数据表建立实体类</h2><img src="/2020/12/14/MyBatis%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/database.png" srcset="/img/loading.gif" class="" title="database.png">
<h3 id="方式1-——-借助IDEA"><a href="#方式1-——-借助IDEA" class="headerlink" title="方式1 —— 借助IDEA"></a>方式1 —— 借助IDEA</h3><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-comment">// 实体类</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> String password;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">()</span> </span>&#123;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">(<span class="hljs-keyword">int</span> id, String name, String pwd)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.id = id;
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.password = pwd;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> id;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(<span class="hljs-keyword">int</span> id)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.id = id;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.name = name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPwd</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> password;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPwd</span><span class="hljs-params">(String pwd)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.password = pwd;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;User&#123;&quot;</span> +
                <span class="hljs-string">&quot;id=&quot;</span> + id +
                <span class="hljs-string">&quot;, name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&quot;, pwd=&#x27;&quot;</span> + password + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;</code></pre>
<h3 id="方式2-——-利用lombok插件"><a href="#方式2-——-利用lombok插件" class="headerlink" title="方式2 —— 利用lombok插件"></a>方式2 —— 利用lombok插件</h3><ol>
<li><p>先给IDEA安装lombok插件</p>
</li>
<li><p>lombok插件提供了众多pojo类注解，可以自动生成get/set/toString/hashCode/无参构造/有参构造等方法，常用的注解有</p>
<p>@Getter/@Setter</p>
<p>@ToString</p>
<p>@Data</p>
<p>@RequiredArgsConstructor</p>
<p>@AllArgsConstructor </p>
<p>@NoArgsConstructor </p>
<p>使用样例如下：</p>
</li>
</ol>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">import</span> lombok.AllArgsConstructor;
<span class="hljs-keyword">import</span> lombok.Data;
<span class="hljs-keyword">import</span> lombok.NoArgsConstructor;

<span class="hljs-comment">// 实体类</span>
<span class="hljs-meta">@Data</span>       <span class="hljs-comment">// 包含get、set方法、无参构造、toString和hashCode等</span>
<span class="hljs-meta">@AllArgsConstructor</span>     <span class="hljs-comment">// 全参构造，会覆盖无参方法</span>
<span class="hljs-meta">@NoArgsConstructor</span>      <span class="hljs-comment">// 无参构造</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> String password;
&#125;</code></pre>
<ol>
<li>导入lombok的jar包</li>
</ol>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.projectlombok<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>lombok<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.18.16<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
<h2 id="3-业务接口定义与实现"><a href="#3-业务接口定义与实现" class="headerlink" title="3. 业务接口定义与实现"></a>3. 业务接口定义与实现</h2><h3 id="方式1-——-直接给dao层添加接口"><a href="#方式1-——-直接给dao层添加接口" class="headerlink" title="方式1 —— 直接给dao层添加接口"></a>方式1 —— 直接给dao层添加接口</h3><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.dao;

<span class="hljs-keyword">import</span> com.youzikeji.pojo.User;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserMapper</span> </span>&#123;
    <span class="hljs-comment">// 查询全部用户</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">getUserList</span><span class="hljs-params">()</span></span>;

    <span class="hljs-comment">// 根据ID查询用户</span>
    <span class="hljs-function">User <span class="hljs-title">getUserById</span><span class="hljs-params">(<span class="hljs-keyword">int</span> id)</span></span>;

    <span class="hljs-comment">// 增加用户</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">addUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-comment">// 修改用户</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">updateUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-comment">// 删除用户</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(<span class="hljs-keyword">int</span> id)</span></span>;

    <span class="hljs-comment">// 模糊查询</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">getSimilarUser</span><span class="hljs-params">(String name)</span></span>;
&#125;
</code></pre>
<p>定义好接口后，新建一个同名的xml文件用于绑定接口并定义实现的sql语句</p>
<pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">mapper</span></span>
<span class="hljs-meta">        <span class="hljs-meta-keyword">PUBLIC</span> <span class="hljs-meta-string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span>
<span class="hljs-meta">        <span class="hljs-meta-string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span>

<span class="hljs-comment">&lt;!--bind Mapper interface--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">&quot;com.youzikeji.dao.UserMapper&quot;</span>&gt;</span>

    <span class="hljs-comment">&lt;!--resultSet Mapping--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">resultMap</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;UserMap&quot;</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">result</span> <span class="hljs-attr">column</span>=<span class="hljs-string">&quot;pwd&quot;</span> <span class="hljs-attr">property</span>=<span class="hljs-string">&quot;password&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">resultMap</span>&gt;</span>
    <span class="hljs-comment">&lt;!--sql command--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;getUserList&quot;</span> <span class="hljs-attr">resultMap</span>=<span class="hljs-string">&quot;UserMap&quot;</span>&gt;</span>
        select * from mybatis.user
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;getUserById&quot;</span> <span class="hljs-attr">resultMap</span>=<span class="hljs-string">&quot;UserMap&quot;</span>&gt;</span>
        select  * from mybatis.user where id = #&#123;id&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;addUser&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span>
        insert into mybatis.user (id, name, pwd) VALUES (#&#123;id&#125;,#&#123;name&#125;,#&#123;pwd&#125;)
    <span class="hljs-tag">&lt;/<span class="hljs-name">insert</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">update</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;updateUser&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span>
        update mybatis.user set name=#&#123;name&#125;, pwd=#&#123;pwd&#125;  where id=#&#123;id&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">update</span>&gt;</span>
    
    <span class="hljs-tag">&lt;<span class="hljs-name">delete</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;deleteUser&quot;</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">&quot;int&quot;</span>&gt;</span>
        delete from mybatis.user where id=#&#123;id&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">delete</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;getSimilarUser&quot;</span> <span class="hljs-attr">resultMap</span>=<span class="hljs-string">&quot;UserMap&quot;</span>&gt;</span>
        select * from mybatis.user where name like concat(&#x27;%&#x27;, #&#123;name&#125; ,&#x27;%&#x27;)
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></code></pre>
<p>ps：</p>
<p>pojo类定义时的属性名和数据表对应位置的字段名不同时，需要进行结果集映射，即resultMap</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--resultSet Mapping--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">resultMap</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;UserMap&quot;</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;user&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">result</span> <span class="hljs-attr">column</span>=<span class="hljs-string">&quot;pwd&quot;</span> <span class="hljs-attr">property</span>=<span class="hljs-string">&quot;password&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">resultMap</span>&gt;</span></code></pre>
<p>绑定好mapper接口之后，需要到<code>resources/mybatis-config.xml</code>文件中注册mapper</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--mapper.xml registering--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">&quot;com/youzikeji/dao/UserMapper.xml&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span></code></pre>
<p>ps：</p>
<p>使用<code>&lt;mapper resource=&quot;&quot;/&gt;</code>方式时，需要填入xml文件的相对路径</p>
<h3 id="方式2-——-使用注解"><a href="#方式2-——-使用注解" class="headerlink" title="方式2 —— 使用注解"></a>方式2 —— 使用注解</h3><p>在定义业务接口时使用注解将方法和对应sql命令进行绑定</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.dao;

<span class="hljs-keyword">import</span> com.youzikeji.pojo.User;
<span class="hljs-keyword">import</span> org.apache.ibatis.annotations.*;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserMapper</span> </span>&#123;
    <span class="hljs-comment">// 查询全部用户,注解实现</span>
    <span class="hljs-meta">@Select(&quot;select * from user&quot;)</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">getUserList</span><span class="hljs-params">()</span></span>;

    <span class="hljs-comment">// 根据ID查询用户</span>
    <span class="hljs-meta">@Select(&quot;select * from user where id = #&#123;id&#125;&quot;)</span>
    <span class="hljs-function">User <span class="hljs-title">getUserById</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;id&quot;)</span> <span class="hljs-keyword">int</span> id)</span></span>;

    <span class="hljs-comment">// 增加用户</span>
    <span class="hljs-meta">@Insert(&quot;insert into user(id, name, pwd) values (#&#123;id&#125;, #&#123;name&#125;, #&#123;password&#125;)&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">addUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-comment">// 修改用户</span>
    <span class="hljs-meta">@Update(&quot;update user set name=#&#123;name&#125;, pwd=#&#123;password&#125; where id=#&#123;id&#125;&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">updateUser</span><span class="hljs-params">(User user)</span></span>;

    <span class="hljs-comment">// 删除用户</span>
    <span class="hljs-meta">@Delete(&quot;delete from user where id=#&#123;uid&#125;&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(<span class="hljs-meta">@Param(&quot;uid&quot;)</span> <span class="hljs-keyword">int</span> id)</span></span>;

    <span class="hljs-comment">// 模糊查询</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">getSimilarUser</span><span class="hljs-params">(String name)</span></span>;
&#125;
</code></pre>
<p>之后直接到<code>resources/mybatis-config.xml</code>文件中注册mapper</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--mapper class registering--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.dao.UserMapper&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span></code></pre>
<h2 id="4-构建mybatis核心配置文件"><a href="#4-构建mybatis核心配置文件" class="headerlink" title="4. 构建mybatis核心配置文件"></a>4. 构建mybatis核心配置文件</h2><p>XML 配置文件中包含了对 MyBatis 系统的核心设置，包括获取数据库连接实例的数据源（DataSource）以及决定事务作用域和控制方式的事务管理器（TransactionManager）。</p>
<pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">configuration</span></span>
<span class="hljs-meta">        <span class="hljs-meta-keyword">PUBLIC</span> <span class="hljs-meta-string">&quot;-//mybatis.org//DTD Config 3.0//EN&quot;</span></span>
<span class="hljs-meta">        <span class="hljs-meta-string">&quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;</span>&gt;</span>
<span class="hljs-comment">&lt;!--core setting--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
    <span class="hljs-comment">&lt;!--load db.properties--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">&quot;db.properties&quot;</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;username&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;root&quot;</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;password&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;root&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-comment">&lt;!--settings--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">settings</span>&gt;</span>
        <span class="hljs-comment">&lt;!--standard log settings--&gt;</span>
<span class="hljs-comment">&lt;!--        &lt;setting name=&quot;logImpl&quot; value=&quot;STDOUT_LOGGING&quot;/&gt;--&gt;</span>
        <span class="hljs-comment">&lt;!--LOG4J setting, need dependency--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;logImpl&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;LOG4J&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span>
    <span class="hljs-comment">&lt;!--set typeAlias--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">typeAliases</span>&gt;</span>
        <span class="hljs-comment">&lt;!--method 1--&gt;</span>
<span class="hljs-comment">&lt;!--        &lt;typeAlias type=&quot;com.youzikeji.pojo.User&quot; alias=&quot;user&quot;/&gt;--&gt;</span>
        <span class="hljs-comment">&lt;!--method 2--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;com.youzikeji.pojo&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">typeAliases</span>&gt;</span>
    <span class="hljs-comment">&lt;!--multi-environments--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">environments</span> <span class="hljs-attr">default</span>=<span class="hljs-string">&quot;development&quot;</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">environment</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;development&quot;</span>&gt;</span>
            <span class="hljs-comment">&lt;!--JDBC--&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">transactionManager</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;JDBC&quot;</span>/&gt;</span>
            <span class="hljs-comment">&lt;!--database connect setting--&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">dataSource</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;POOLED&quot;</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;driver&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;$&#123;driver&#125;&quot;</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;url&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;$&#123;url&#125;&quot;</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;username&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;$&#123;username&#125;&quot;</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;password&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;$&#123;password&#125;&quot;</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">dataSource</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">environment</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">environments</span>&gt;</span>

    <span class="hljs-comment">&lt;!--mapper class registering--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.dao.UserMapper&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span></code></pre>
<p>关于配置文件的说明：</p>
<ol>
<li><p>所有核心的配置都在<code>&lt;configuration&gt;...&lt;/configuration&gt;</code>中，其中，各部分配置需要遵从既定的顺序。</p>
<p>前三个按顺序必须依次是<code>&lt;properties&gt; ——&gt; &lt;settings&gt; ——&gt; &lt;typeAliases&gt;</code>.</p>
<p>另外<code>&lt;mappers&gt;</code>必须在最后进行注册配置；</p>
</li>
<li><p><code>&lt;properties&gt;</code>，顾名思义，可以在这里配置属性.</p>
<p>这些属性可以在外部进行配置，并可以进行动态替换。</p>
<p>这说明既可以在java属性文件<code>resources/*.properties</code>中配置这些属性，也可以在<code>&lt;property&gt;</code>中设置。</p>
<p>在<code>db.properties</code>中的配置为：</p>
<pre><code class="hljs properties"><span class="hljs-attr">driver</span>=<span class="hljs-string">com.mysql.jdbc.Driver</span>
<span class="hljs-attr">url</span>=<span class="hljs-string">jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai</span></code></pre>
<p>在<code>&lt;properties&gt;</code>的子属性<code>&lt;property&gt;</code>中的配置如下：</p>
<pre><code class="hljs properties"><span class="hljs-meta">&lt;!--load</span> <span class="hljs-string">db.properties--&gt;</span>
<span class="hljs-meta">&lt;properties</span> <span class="hljs-string">resource=&quot;db.properties&quot;&gt;</span>
    <span class="hljs-meta">&lt;property</span> <span class="hljs-string">name=&quot;username&quot; value=&quot;root&quot;/&gt;</span>
    <span class="hljs-meta">&lt;property</span> <span class="hljs-string">name=&quot;password&quot; value=&quot;root&quot;/&gt;</span>
<span class="hljs-attr">&lt;/properties&gt;</span></code></pre>
</li>
<li><p><code>&lt;settings&gt;</code>作为MyBatis 中极为重要的调整设置，它们会改变 MyBatis 的运行时行为。 一个配置完整的 settings 元素的示例如下：</p>
</li>
</ol>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">settings</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;cacheEnabled&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span>		<span class="hljs-comment">&lt;!--全局性地开启或关闭所有映射器配置文件中已配置的任何缓存--&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;lazyLoadingEnabled&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span>  <span class="hljs-comment">&lt;!--延迟加载的全局开关。当开启时，所有关联对象都会延迟加载--&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;multipleResultSetsEnabled&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;useColumnLabel&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;useGeneratedKeys&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;autoMappingBehavior&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;PARTIAL&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;autoMappingUnknownColumnBehavior&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;WARNING&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;defaultExecutorType&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;SIMPLE&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;defaultStatementTimeout&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;25&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;defaultFetchSize&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;100&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;safeRowBoundsEnabled&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;mapUnderscoreToCamelCase&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;false&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;localCacheScope&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;SESSION&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;jdbcTypeForNull&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;OTHER&quot;</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;lazyLoadTriggerMethods&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;equals,clone,hashCode,toString&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span></code></pre>
<p>特别的，只是简单在<code>&lt;settings&gt;</code>中进行日志配置，可以使用自带的标准日志，也可使用log4j，使用log4j的步骤如下：</p>
<ul>
<li>前提——导入log4j的jar包</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>log4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>log4j<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2.17<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
<ul>
<li>编写日志的属性文件<code>resources/log4j.properties</code></li>
</ul>
<pre><code class="hljs properties"><span class="hljs-comment">#将等级为DEBUG的日志信息输出到控制台和file两个目的地</span>
<span class="hljs-meta">log4j.rootLogger</span> = <span class="hljs-string">DEBUG,console,file</span>

<span class="hljs-comment">#控制台输出相关配置</span>
<span class="hljs-meta">log4j.appender.console</span> = <span class="hljs-string">org.apache.log4j.ConsoleAppender</span>
<span class="hljs-meta">log4j.appender.console.Target</span> = <span class="hljs-string">System.out</span>
<span class="hljs-meta">log4j.appender.console.Threshold</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.appender.console.layout</span> = <span class="hljs-string">org.apache.log4j.PatternLayout</span>
<span class="hljs-meta">log4j.appender.console.layout.ConversionPatten</span> = <span class="hljs-string">[%c]-%m%n</span>

<span class="hljs-comment">#文件输出相关设置</span>
<span class="hljs-meta">log4j.appender.file</span> = <span class="hljs-string">org.apache.log4j.RollingFileAppender</span>
<span class="hljs-meta">log4j.appender.file.File</span> = <span class="hljs-string">./log/youzikeji.log</span>
<span class="hljs-meta">log4j.appender.file.MaxFileSize</span> = <span class="hljs-string">10mb</span>
<span class="hljs-meta">log4j.appender.file.Threshold</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.appender.file.layout</span> = <span class="hljs-string">org.apache.log4j.PatternLayout</span>
<span class="hljs-meta">log4j.appender.file.layout.ConversionPatten</span> = <span class="hljs-string">[%p][%d&#123;yy-MM-dd&#125;][%c]%m%n</span>

<span class="hljs-comment">#日志输出级别</span>
<span class="hljs-meta">log4j.logger.org.mybatis</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.logger.java.sql</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.logger.java.sql.Statement</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.logger.java.sql.ResultSet</span> = <span class="hljs-string">DEBUG</span>
<span class="hljs-meta">log4j.logger.java.sql.PreparedStatement</span> = <span class="hljs-string">DEBUG</span></code></pre>
<ul>
<li>在<code>&lt;setting&gt;</code>中配置</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">settings</span>&gt;</span>
    <span class="hljs-comment">&lt;!--LOG4J setting, need dependency--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;logImpl&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;LOG4J&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">settings</span>&gt;</span></code></pre>
<ol>
<li><p><code>&lt;typeAliases&gt;</code>为取别名的配置，有两种方式取别名</p>
</li>
<li><p>传统方式</p>
</li>
</ol>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">typeAliases</span>&gt;</span>
    <span class="hljs-comment">&lt;!--method 1--&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">typeAlias</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.User&quot;</span> <span class="hljs-attr">alias</span>=<span class="hljs-string">&quot;user&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">typeAliases</span>&gt;</span></code></pre>
<ol>
<li>声明包名方式——(该包下的类的别名默认为其小写形式)</li>
</ol>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">typeAliases</span>&gt;</span>
    <span class="hljs-comment">&lt;!--method 2--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;com.youzikeji.pojo&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">typeAliases</span>&gt;</span></code></pre>
<h2 id="5-从XML中构建SqlSessionFactory"><a href="#5-从XML中构建SqlSessionFactory" class="headerlink" title="5. 从XML中构建SqlSessionFactory"></a>5. 从XML中构建SqlSessionFactory</h2><p>MyBatis 包含一个名叫 Resources 的工具类，它包含一些实用方法，使得从类路径或其它位置加载资源文件更加容易。</p>
<pre><code class="hljs java">String resource = <span class="hljs-string">&quot;org/mybatis/example/mybatis-config.xml&quot;</span>;
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(inputStream);</code></pre>
<p>由XML文件生成SqlSessionFactory对象这一步骤是既定的，可以包装成工具类MybatisUtils</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.utils;

<span class="hljs-keyword">import</span> org.apache.ibatis.io.Resources;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactoryBuilder;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.InputStream;

<span class="hljs-comment">// Mybatis工具类</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MybatisUtils</span> </span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> SqlSessionFactory sqlSessionFactory;
    <span class="hljs-keyword">static</span> &#123;
        <span class="hljs-comment">// 使用Mybatis第一步：获取sqlSessionFactory对象</span>
        <span class="hljs-keyword">try</span> &#123;
            String resource = <span class="hljs-string">&quot;mybatis-config.xml&quot;</span>;
            <span class="hljs-comment">// 将XML文件读入输入流</span>
            InputStream inputStream = Resources.getResourceAsStream(resource);
            <span class="hljs-comment">// 从XML文件中构建 SqlSessionFactory 的实例</span>
            sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(inputStream);

        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
    <span class="hljs-comment">// 第二步：获取SqlSession对象</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> SqlSession <span class="hljs-title">getSqlSession</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> sqlSessionFactory.openSession();
    &#125;
&#125;</code></pre>
<h2 id="6-由SqlSessionFactory获取SqlSession"><a href="#6-由SqlSessionFactory获取SqlSession" class="headerlink" title="6. 由SqlSessionFactory获取SqlSession"></a>6. 由SqlSessionFactory获取SqlSession</h2><p>在MybatisUtils类中定义了一个方法，通过调用openSession()获取SqlSession对象</p>
<pre><code class="hljs java">SqlSession session = MybatisUtils.getSqlSession();</code></pre>
<h2 id="7-编写测试类"><a href="#7-编写测试类" class="headerlink" title="7. 编写测试类"></a>7. 编写测试类</h2><p>获取SqlSession对象后，通过<code>getMapper()</code>方法获取Mapper对象，通过Mapper对象调用接口方法执行SQL语句</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.dao;

<span class="hljs-keyword">import</span> com.youzikeji.pojo.User;
<span class="hljs-keyword">import</span> com.youzikeji.utils.MybatisUtils;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;
<span class="hljs-keyword">import</span> org.apache.log4j.Logger;
<span class="hljs-keyword">import</span> org.junit.Test;

<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserMapperTest</span> </span>&#123;

    <span class="hljs-comment">//通过反射获取本类的日志对象</span>
    <span class="hljs-keyword">static</span> Logger logger  = Logger.getLogger(UserMapperTest.class);

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-comment">// 1.获取SqlSession对象</span>
        SqlSession session = MybatisUtils.getSqlSession();
        <span class="hljs-comment">// 2.执行SQL(getmapper())</span>
        UserMapper mapper = session.getMapper(UserMapper.class);
        List&lt;User&gt; list = mapper.getUserList();

        <span class="hljs-keyword">for</span> (User user : list) &#123;
            System.out.println(user);
        &#125;
        <span class="hljs-comment">// 3.关闭SqlSession</span>
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getUserById</span><span class="hljs-params">()</span></span>&#123;
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        User user = mapper.getUserById(<span class="hljs-number">1</span>);
        System.out.println(user);
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span></span>&#123;
        SqlSession session = MybatisUtils.getSqlSession();

        UserMapper mapper = session.getMapper(UserMapper.class);

        mapper.addUser(<span class="hljs-keyword">new</span> User(<span class="hljs-number">4</span>,<span class="hljs-string">&quot;lalalalal&quot;</span>, <span class="hljs-string">&quot;111111&quot;</span>));

        <span class="hljs-comment">// autocommit=true ——&gt; 自动提交事务</span>
        session.commit();
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span></span>&#123;
        SqlSession session = MybatisUtils.getSqlSession();

        UserMapper mapper = session.getMapper(UserMapper.class);

        mapper.updateUser(<span class="hljs-keyword">new</span> User(<span class="hljs-number">4</span>, <span class="hljs-string">&quot;nba&quot;</span>, <span class="hljs-string">&quot;111112&quot;</span>));

        session.commit();
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">()</span></span>&#123;
        SqlSession session = MybatisUtils.getSqlSession();

        UserMapper mapper = session.getMapper(UserMapper.class);

        mapper.deleteUser(<span class="hljs-number">4</span>);

        session.commit();
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getSimilarUser</span><span class="hljs-params">()</span></span>&#123;
        SqlSession session = MybatisUtils.getSqlSession();

        UserMapper mapper = session.getMapper(UserMapper.class);

        List&lt;User&gt; users = mapper.getSimilarUser(<span class="hljs-string">&quot;an&quot;</span>);

        <span class="hljs-keyword">for</span> (User user : users) &#123;
            System.out.println(user);
        &#125;
        session.close();
    &#125;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testLog4j</span><span class="hljs-params">()</span></span>&#123;
        logger.info(<span class="hljs-string">&quot;info —— 我在测试testLog4j&quot;</span>);
        logger.debug(<span class="hljs-string">&quot;debug —— 我在测试testLog4j&quot;</span>);
        logger.error(<span class="hljs-string">&quot;error —— 我在测试testLog4j&quot;</span>);
    &#125;
&#125;
</code></pre>
<h2 id="8-动态SQL"><a href="#8-动态SQL" class="headerlink" title="8. 动态SQL"></a>8. 动态SQL</h2><p>参考<a target="_blank" rel="noopener" href="https://mybatis.org/mybatis-3/zh/dynamic-sql.html">官方文档</a></p>
<h2 id="9-MyBatis缓存"><a href="#9-MyBatis缓存" class="headerlink" title="9. MyBatis缓存"></a>9. MyBatis缓存</h2><h3 id="缓存基础"><a href="#缓存基础" class="headerlink" title="缓存基础"></a>缓存基础</h3><p>MyBatis中默认定义了两级缓存：<code>一级缓存</code>和<code>二级缓存</code></p>
<ul>
<li><p>默认只开启一级缓存，SqlSession(会话)级别的缓存，也称为<code>本地缓存</code></p>
</li>
<li><p>二级缓存需要手动开启，基于<code>namespace</code>(接口)级别的缓存</p>
<ul>
<li><p>所有数据都会先放在一级缓存中，当会话提交或者关闭时，数据才会提交到二级缓存中</p>
</li>
<li><p>要启用全局的二级缓存，只需要在 SQL 映射文件中添加一行：<code>&lt;cache/&gt;</code>，该语句的效果如下:</p>
<ul>
<li>映射语句文件中的所有 select 语句的结果将会被缓存</li>
<li>映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存</li>
<li>缓存默认会使用<code>最近最少使用</code>算法（LRU, Least Recently Used）算法来清除不需要的缓存<ul>
<li>可用的清除策略有：<ul>
<li><code>LRU</code> – 最近最少使用：移除最长时间不被使用的对象。</li>
<li><code>FIFO</code> – 先进先出：按对象进入缓存的顺序来移除它们。</li>
<li><code>SOFT</code> – 软引用：基于垃圾回收器状态和软引用规则移除对象。</li>
<li><code>WEAK</code> – 弱引用：更积极地基于垃圾收集器状态和弱引用规则移除对象。</li>
</ul>
</li>
</ul>
</li>
<li>缓存默认不会定时进行刷新</li>
<li>缓存会保存列表或对象（无论查询方法返回哪种）的 1024 个引用。</li>
<li>缓存会被视为读/写缓存，这意味着获取到的对象并不是共享的，可以安全地被调用者修改，而不干扰其他调用者或线程所做的潜在修改。</li>
</ul>
</li>
<li><p>二级缓存的属性可以通过 cache 元素的属性来修改：</p>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">cache</span></span>
<span class="hljs-tag">  <span class="hljs-attr">eviction</span>=<span class="hljs-string">&quot;FIFO&quot;</span></span>
<span class="hljs-tag">  <span class="hljs-attr">flushInterval</span>=<span class="hljs-string">&quot;60000&quot;</span> </span>
<span class="hljs-tag">  <span class="hljs-attr">size</span>=<span class="hljs-string">&quot;512&quot;</span></span>
<span class="hljs-tag">  <span class="hljs-attr">readOnly</span>=<span class="hljs-string">&quot;true&quot;</span>/&gt;</span></code></pre>
<p>上面语句的效果如下：</p>
<ul>
<li>创建了一个 FIFO 缓存</li>
<li>每隔 60 秒刷新</li>
<li>最多可以存储结果对象或列表的 512 个引用</li>
<li>返回的对象被认为是只读的，因此对它们进行修改可能会在不同线程中的调用者产生冲突。</li>
</ul>
</li>
</ul>
</li>
<li><p>为了提高扩展性，定义了<code>缓存接口Cache</code>，可以通过实现Cache接口来自定义二级缓存</p>
<p>Cache接口</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> org.apache.ibatis.cache;

<span class="hljs-keyword">import</span> java.util.concurrent.locks.ReadWriteLock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Cache</span> </span>&#123;
    <span class="hljs-function">String <span class="hljs-title">getId</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">putObject</span><span class="hljs-params">(Object var1, Object var2)</span></span>;

    <span class="hljs-function">Object <span class="hljs-title">getObject</span><span class="hljs-params">(Object var1)</span></span>;

    <span class="hljs-function">Object <span class="hljs-title">removeObject</span><span class="hljs-params">(Object var1)</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">clear</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getSize</span><span class="hljs-params">()</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">default</span> ReadWriteLock <span class="hljs-title">getReadWriteLock</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    &#125;
&#125;</code></pre>
<p>自定义缓存方式请参考官方文档<a target="_blank" rel="noopener" href="https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache">MyBatis缓存</a></p>
</li>
</ul>
<h3 id="缓存原理"><a href="#缓存原理" class="headerlink" title="缓存原理"></a>缓存原理</h3><img src="/2020/12/14/MyBatis%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/%E7%BC%93%E5%AD%98%E5%8E%9F%E7%90%86.png" srcset="/img/loading.gif" class="" title="缓存原理.png">

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/MyBatis/">MyBatis</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Spring基础知识</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/11/25/%E5%9F%BA%E4%BA%8E%E5%A4%9A%E7%9F%A5%E8%AF%86%E5%BA%93%E8%BF%AD%E4%BB%A3%E6%A3%80%E7%B4%A2%E7%9A%84%E5%B8%B8%E8%AF%86%E9%97%AE%E7%AD%94%E7%B3%BB%E7%BB%9F/">
                        <span class="hidden-mobile">基于多知识库迭代检索的常识问答系统</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "MyBatis基础知识&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  











</body>
</html>
